package asynchronous

import (
	"duoke/internal/model/entity"
	"duoke/model"
	"duoke/service"
	"duoke/utils/redislib"
	"duoke/utils/yaml"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/sirupsen/logrus"
)

type SeparateService struct {
	stream *redislib.RedisStream
}

func NewSeparateService(stream *redislib.RedisStream) *SeparateService {
	return &SeparateService{
		stream: stream,
	}
}

// SendNotification 发送通知消息
func (s *SeparateService) SendNotification(message map[string]interface{}) {
	err := s.stream.Publish(message)
	if err != nil {
		fmt.Printf("Failed to publish message: %v\n", err)
	}
	fmt.Println("已发布消息:", message)
}

// StartListening 启动监听器
func (s *SeparateService) StartListening(c *gin.Context) {
	fmt.Println("开始监听消息...")
	s.stream.Consume(func(message map[string]interface{}) error {
		// 模拟业务逻辑
		config := yaml.GetConfig()
		if gconv.String(message["type"]) == "bind_user" {
			if config.SubMch.SubType == "2" {
				return nil
			}
			err := s.BindUser(c, message)
			if err != nil {
				logrus.Error("商户绑定用户失败：" + err.Error())
				return fmt.Errorf("绑定用户失败")
			}
		}
		if gconv.String(message["type"]) == "separate_accounts" {
			if config.SubMch.SubType == "2" {
				return nil
			}
			err := s.SeparateAccounts(c, message)
			if err != nil {
				logrus.Error("分账失败：" + err.Error())
				return fmt.Errorf("分账失败")
			}
		}
		if gconv.String(message["type"]) == "batches" {
			err := s.batches(c, message)
			if err != nil {
				logrus.Error("提现失败：" + err.Error())
				return fmt.Errorf("提现失败")
			}
		}
		return nil
	})
}

// BindUser 绑定用户
func (s *SeparateService) BindUser(c *gin.Context, req map[string]interface{}) error {
	var m model.ReqSubAccount
	err := gconv.Struct(req["content"], &m)
	if err != nil {
		return err
	}
	m.ReceivierRelationType = "PERSONAL_OPENID"
	// 先绑定用户
	err = service.SeparateAccounts.BindUser(c, &m)
	if err != nil {
		return err
	}
	return err
}
func (s *SeparateService) SeparateAccounts(c *gin.Context, req map[string]interface{}) error {
	var m model.SeparateApply
	err := gconv.Struct(req["content"], &m)
	if err != nil {
		return err
	}
	err = service.SeparateAccounts.SeparateAccountsV3(c, &m)
	if err != nil {
		return err
	}
	return nil
}

// 提现金额
func (s *SeparateService) batches(c *gin.Context, req map[string]interface{}) error {
	var m model.Transfer
	err := gconv.Struct(req["content"], &m)
	if err != nil {
		return err
	}
	isSuccess, err := service.WechatPay.PartnerTransfer(c, &m)
	if err != nil {
		return err
	}
	info, err := service.Withdrawal.Info(c, &model.SearchWithdrawal{Id: m.WithdrawalId})
	if err != nil {
		return err
	}
	if info.State == 3 {
		return nil
	}
	if isSuccess.Code == 0 {
		withdrawal := entity.WithdrawalLog{
			UserId:         m.UserId,
			OutBillNo:      m.OutBillNo,
			TransferBillNo: isSuccess.Response.TransferBillNo,
			State:          isSuccess.Response.State,
			Openid:         m.Openid,
			Avatar:         m.Avatar,
			TotalAmount:    m.TransferAmount,
			WithdrawalId:   m.WithdrawalId,
			PackageInfo:    isSuccess.Response.PackageInfo,
		}
		err = service.Withdrawal.Save(c, &withdrawal)
		if err != nil {
			return err
		}
	}
	return err
}
